<?php


namespace App\Http\Controllers\Api;

use App\Events\OrderDelivery;
use App\Events\OrderPaySuccess;
use App\Events\OrderReceive;
use App\Models\Escort;
use App\Models\Order;
use App\Models\School;
use App\Models\Shop;
use App\Services\ChatService;
use App\Services\RealNameService;
use Illuminate\Http\Request;

/**
 * 镖师控制
 * Class EscortController
 * @package App\Http\Controllers\Api
 */
class EscortController extends Controller
{
    /**
     * 镖师申请
     */
    public function apply()
    {
        $data = request()->all();
        $idcard = $data['idcard'];
        $realname = $data['realname'];
        $phone = $data['phone'];
        $address = $data['address'];
        $material = $data['material'];

        /*判断当前用户有没有申请过*/
        $escort = Escort::whereUid($this->uid)
            ->first();
        if($escort){
            if($escort->status == 0){
                return $this->error(-1,'您的申请已在审核中,请耐心等待');
            }elseif($escort->status == 1){
                return $this->error(-1,'您已是镖师,请勿重复申请');
            }elseif($escort->status == 2){
                return $this->error(-1,'您已是镖师,请勿重复申请');
            }
        }
        //聚合借口校验身份证实名对不对
//        $real_result = RealNameService::realName([
//            'realname' => $realname,
//            'idcard' => $idcard
//        ]);
//        if($real_result['status'] != 0 ){
//            return $this->error(-1, $real_result['msg']);
//        }

        if($escort){
            $escort->realname = $realname;
            $escort->phone = $phone;
            $escort->address = $address;
            $escort->material = $material;
            $escort->status = 0;
            $escort->role = $this->userInfo->is_leader?2:1;
            $escort->save();
        }else{
            Escort::create([
                'uid' => $this->uid,
                'realname' => $realname,
                'phone' => $phone,
                'address' => $address,
                'material' => $material,
                'role' => $this->userInfo->is_leader?2:1,
                'avatar' => $this->userInfo->avatar,
                'status' => 0
            ]);
        }

        $this->success('','提交成功');
    }

    /**
     * 抢单大厅
     */
    public function orderHall(Request $request)
    {
        $school_id = $request->input('school_id',0);
        $shop_id = $request->input('shop_id',0);
        $escort = Escort::whereKey($this->escort_id)->where('status','!=',0)->first();
        if(!$escort->status){
            return $this->error('-1', '您的镖师还在审核中...');
        }
        $model = Order::whereIn('type',[1,10])->whereStatus(1)->with('school')
            ->select(['id','add_time','school_name','from_name', 'from_phone', 'from_address','to_pic', 'to_address', 'order_id', 'to_school_id','to_name', 'to_phone', 'out_trade_no','order_extend'])
            ->whereIn('school_id',explode(',',$escort->school_ids));
        if($school_id && in_array($school_id,explode(',',$escort->school_ids))){
            $model->where('school_id',$school_id);
        }
        if($shop_id){
            $model->where('shop_id',$shop_id);
        }
        $orders = $model->paginate();
        $this->success($orders);
    }

    //筛选订单
    public function choose(Request $request){
        $escort_info = Escort::where('uid',$this->uid)->where('status','!=',0)->first();
        if(empty($escort_info)){
            return $this->error(-1,'配送信息异常');
        }
        $model = Order::whereIn('type',[10])->whereStatus(1);
        if($escort_info['school_ids']){
            $model->whereIn('school_id',explode(',',$escort_info['school_ids']));
        }
        $my_school_ids = explode(',',$escort_info->school_ids);
        $orders = $model->get()->toArray();
        $shops_all = array_count_values(array_column($orders,'shop_id'));
        $schools_all = array_count_values(array_column($orders,'school_id'));

        $shops = [];
        $schools = [];
        $i = 0;

        foreach ($shops_all as $key=>$item){
            $shops[$i]['num'] = $item;
            $shops[$i]['shop_id'] = $key;
            $shops[$i]['shop_name'] = Shop::where('id',$key)->value('name');
            $i++;
        }
        $j = 0;
        foreach ($schools_all as $key=>$item){
            if(in_array($key,$my_school_ids)){
                $schools[$j]['num'] = $item;
                $schools[$j]['school_id'] = $key;
                $schools[$j]['school_name'] = School::where('id',$key)->value('name');
                $j++;
            }
        }
        $this->success(['shops'=>$shops,'schools'=>$schools]);

    }


    /**
     * 修改镖师状态
     */
    public function changeState()
    {
        $escort = Escort::whereKey($this->escort_id)->first();
        if($escort->status == 0){
            return $this->error(-1,'审核中');
        }
        $escort->status = $escort->status==1?2:1;
        $escort->save();

        return $this->success('', '操作成功');
    }

    /**
     * 我的任务
     */
    public function myTask()
    {
        $escort_info = Escort::where('uid',$this->uid)->where('status','!=',0)->first();
        if(empty($escort_info)){
            return $this->error(-1,'配送员信息异常');
        }
        $type = request()->input('type');
        $keywords = request()->input('keywords');
        $query =  Order::whereIn('type', [1, 10]);
        if($type == 1){
            $query->whereStatus(2);
        }else{
            $query->whereStatus(3);
        }
        if($keywords){
            $query->where(function($query)use($keywords){
                $query->where('from_name', 'like', "%{$keywords}%")
                    ->orWhere('from_phone', $keywords)
                    ->orWhere('from_address', 'like', "%{$keywords}%")
                    ->orWhere('to_address', 'like', "%{$keywords}%");
            });
        }
        $orders = $query->whereEscortId($this->escort_id)->with('school')
            ->select(['id', 'add_time','school_name','from_name', 'from_phone', 'from_address', 'to_pic', 'to_address', 'status', 'pay_type', 'order_id', 'to_school_id', 'to_name', 'to_phone', 'out_trade_no','order_extend'])
            ->paginate();
        $this->success($orders);
    }

    /**
     * 接单
     */
    public function receive()
    {
        $orderId = request()->input('order_id');
        $order = Order::whereOrderId($orderId)->whereStatus(1)->first();
        if(!$orderId || !$order){
            return $this->error(-1, '订单错误');
        }
        if($order->status >= 2){
            return $this->error(-1, '手慢了，订单已被抢了');
        }

        $order->status = 2;
        $order->notify_times = 0;
        $order->notify_complete = 0;
        $order->escort_id = $this->escort_id;
        $order->escort_receive_time = time();
        $order->save();

        event(new OrderReceive($order));

        $this->success('', '接单成功');
    }

    /**
     * 送达
     * @throws \Exception
     */
    public function delivery()
    {
        $orderId = request()->input('order_id');

        $order = Order::whereOrderId($orderId)->whereStatus(2)->first();
        if(!$orderId || !$order){
            return $this->error(-1, '订单错误');
        }
        $order->status = 3;
        $order->notify_times = 0;
        $order->notify_complete = 0;
        $order->escort_finish_time = time();

        $order->save();

        event(new OrderDelivery($order));
        $this->success('', '送达成功');
    }


}
